package com.smartlazy.delay.queue.core.service;

import com.smartlazy.delay.queue.core.bean.BucketItem;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Set;

/**
 *
 * @author howe
 */
@Slf4j
@Service
public class DelayBucket implements Serializable {

    @Resource
    private RedisTemplate<String, String> redisTemplate;
    /**
     * 添加JobId到bucket中
     * @param key
     * @param timestamp
     * @param jobId
     */
    public Boolean pushToBucket(String key, long timestamp, String jobId) {
        ZSetOperations<String, String> vo = redisTemplate.opsForZSet();
        return vo.add(key, jobId, timestamp);
    }

    /**
     * 从bucket中获取延迟时间最小的JobId
     */
    public BucketItem getFromBucket(String key) {
        ZSetOperations<String, String> vo = redisTemplate.opsForZSet();
        Set<ZSetOperations.TypedTuple<String>> tuples = vo.rangeWithScores(key,0 ,0);
        if (tuples != null && tuples.size() > 0) {
            for (ZSetOperations.TypedTuple<String> tuple : tuples) {
                BucketItem ret = new BucketItem();
                ret.setJobId(tuple.getValue());
                ret.setTimestamp(tuple.getScore());
                return ret;
            }
        }
        return null;
    }

    /**
     * 从bucket中删除JobId
     */
    public long removeFromBucket(String key, String jobId) {
        ZSetOperations<String, String> vo = redisTemplate.opsForZSet();
        return vo.remove(key, jobId);
    }
}
